<template>
  <div class="container overflow-hidden">
    <div class="center-board">
      <div class="center-title">
        <h3>模版-富文本</h3>
      </div>
      <div class="action-bar mb-[20px]">
        <el-button icon="Back" type="primary" plain text @click="backTo">返回</el-button>
        <el-button icon="Download" type="success" plain @click="saveArticle">保存文章</el-button>
        <!-- <el-button class="copy-btn-main" icon="DocumentCopy" type="primary" text @click="copy">
          复制代码
        </el-button> -->
        <el-button class="delete-btn" icon="Delete" plain type="danger" @click="empty">
          清空
        </el-button>
      </div>
      <EditorForm ref="formRef" :default-data="defaltBaseFormData" :has-category="hasCategory">
        <!-- 如果存在插槽，则显示插槽内容 -->
        <template #default v-if="$slots.extraJson">
          <slot name="extraJson"></slot>
        </template>
      </EditorForm>

      <!-- <el-scrollbar class="center-scrollbar">
        <el-row class="center-board-row" :gutter="formConf.gutter">
          <el-form
            ref="componentFormRef"
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'"
            :rules="dymaticRules"
          >
            <draggable
              class="drawing-board"
              :list="drawingList"
              :animation="340"
              group="componentsGroup"
              item-key="label"
            >
              <template #item="{ element, index }">
                <draggable-item
                  :key="element.renderKey"
                  :drawing-list="drawingList"
                  :element="element"
                  :index="index"
                  :active-id="activeId"
                  :form-conf="formConf"
                  @activeItem="activeFormItem"
                  @copyItem="drawingItemCopy"
                  @deleteItem="drawingItemDelete"
                />
              </template>
            </draggable>
          </el-form>
        </el-row>
      </el-scrollbar> -->
    </div>
    <input id="copyNode" type="hidden" />
  </div>
</template>

<script setup>
import { addArticle, updateArticle } from "@/api/article";
import EditorForm from "./editorForm.vue";
import { typeIdEnum } from "@/utils/articleConfig";
import draggable from "vuedraggable/dist/vuedraggable.common";
const reallyUrl = import.meta.env.VITE_API_IMAGE;
import { defineEmits } from "vue";
const formRef = ref(null);
import {
  articleConfigComponents,
  articleConfigObjectComponents,
  formConf as formConfData,
  defaultArticleConfig,
} from "@/utils/articleConfig";
import { articleTemplateType } from "@/enums/aritcle/aritcle";
import { onMounted, watch } from "vue";
const props = defineProps({
  type: {
    type: Number,
    default: 1,
  },
  defaultData: {
    type: Object,
    default: null,
  },
  hasCategory: {
    default: true,
  },
  // 新增装修知识-富文本：添加简介和缩略图字段，其余的富文本情况没有
  articleExtraJson: {
    type: Object,
    default: () => null,
  },
  articleExtraJsonRef: {
    type: Object,
    default: () => null,
  },
});

const drawingList = ref([]);
const componentFormRef = ref(null);
const { proxy } = getCurrentInstance();
const idGlobal = ref(100);
const activeData = ref();
const activeId = ref();
const isEdit = ref(!!props.defaultData);
const formData = ref({});
const formConf = ref(formConfData);
/**
 * 表单数据
 *
 */
const cmsArticle = ref({
  title: "",
  sort: 1,
  categoryId: "",
  type: props.type,
  templateType: articleTemplateType.IMAGE_TEXT_EDITOR,
  image: "",
});
/***
 * 移动层面的代码
 */
let oldActiveId;
let tempActiveData;
const emit = defineEmits(["backTo"]);

function backTo() {
  emit("backTo");
}
function activeFormItem(element) {
  activeData.value = element;
  activeId.value = element.formId;
}

function empty() {
  ElMessageBox.confirm("确定要清空所有内容吗？", "提示", { type: "warning" }).then(() => {
    idGlobal.value = 100;
    formRef.value.cmsArticle = {
      title: "",
      sort: 1,
      categoryId: "",
      type: props.type,
      templateType: articleTemplateType.IMAGE_TEXT_EDITOR,
      image: [],
    };
    props.articleExtraJson.intro = "";
    props.articleExtraJson.thumbnail = [];
  });
}

function onEnd(obj, a) {
  if (obj.from !== obj.to) {
    activeData.value = tempActiveData;
    activeId.value = idGlobal.value;
  }
}

function addComponent(item) {
  const clone = cloneComponent(item);
  drawingList.value.push(clone);
  activeFormItem(clone);
}

function cloneComponent(origin) {
  const clone = JSON.parse(JSON.stringify(origin));
  clone.formId = ++idGlobal.value;
  clone.span = formConf.value.span;
  clone.renderKey = +new Date(); // 改变renderKey后可以实现强制更新组件
  if (!clone.layout) clone.layout = "colFormItem";
  if (clone.layout === "colFormItem") {
    clone.vModel = `field${idGlobal.value}`;
    clone.placeholder !== undefined && (clone.placeholder += clone.label);
    tempActiveData = clone;
  } else if (clone.layout === "rowFormItem") {
    delete clone.label;
    clone.componentName = `row${idGlobal.value}`;
    clone.gutter = formConf.value.gutter;
    tempActiveData = clone;
  }
  return tempActiveData;
}

function drawingItemCopy(item, parent) {
  let clone = JSON.parse(JSON.stringify(item));
  clone = createIdAndKey(clone);
  parent.push(clone);
  activeFormItem(clone);
}

function createIdAndKey(item) {
  item.formId = ++idGlobal.value;
  item.renderKey = +new Date();
  if (item.layout === "colFormItem") {
    item.vModel = `field${idGlobal.value}`;
  } else if (item.layout === "rowFormItem") {
    item.componentName = `row${idGlobal.value}`;
  }
  if (Array.isArray(item.children)) {
    item.children = item.children.map((childItem) => createIdAndKey(childItem));
  }
  return item;
}

function drawingItemDelete(index, parent) {
  parent.splice(index, 1);
  nextTick(() => {
    const len = drawingList.value.length;
    if (len) {
      activeFormItem(drawingList.value[len - 1]);
    }
  });
}

/**
 *
 *
 * 文章保存更新
 *
 *
 *
 */
function saveArticle() {
  const baseFormData = formRef.value.cmsArticle;

  const newBlockList = [];
  if (baseFormData.text == "<p><br></p>" || baseFormData.text == "<p> </p>") {
    ElMessage.error("请输入内容");
    return 0;
  }
  let block = {
    //item.articleId = item.label
    type: 5,
    text: baseFormData.text,
    sort: 1,
  };
  if (blockId.value) {
    block.id = blockId.value;
  }
  newBlockList.push(block);
  // formData.value = { blocks: JSON.parse(JSON.stringify(drawingList.value)) }
  // 基础的form验证
  formRef.value.getEditorFormRef().validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {
      type: props.type,
      templateType: articleTemplateType.IMAGE_TEXT_EDITOR,
      ...baseFormData,
      image: JSON.stringify(baseFormData.image), // 主图只有一张，字符串
      blocks: newBlockList,
    };
    // 如果存在插槽，则需要添加插槽内容的字段
    if (props.articleExtraJsonRef) {
      props.articleExtraJsonRef.validate((valid) => {
        console.log(valid, "valid");
        if (!valid) {
          return;
        }
      });
      Object.assign(params, handleExtraJson(params));
    }
    //有默认值说明是编辑文章，需要添加方法和id
    if (props.defaultData) {
      params.id = props.defaultData.id;
      methodUpdateArticle(params);
    } else {
      methodAddArticle(params);
    }
  });
}
/**
 * 处理插槽内容
 * @param params
 */
function handleExtraJson(params) {
  if (props.articleExtraJson) {
    return {
      extraJson: {
        intro: props.articleExtraJson.intro,
        thumbnail: JSON.stringify(props.articleExtraJson.thumbnail),
      },
    };
  }
  return {};
}
// 新增文章
async function methodAddArticle(params) {
  try {
    await addArticle(params);
    backTo();
  } catch (err) {
    console.log(err);
  } finally {
    console.log("finally");
  }
}
// 修改文章
async function methodUpdateArticle(params) {
  try {
    await updateArticle(params);
    ElMessage.success("修改成功");
    backTo();
  } catch (err) {
    console.log(err);
  } finally {
    console.log("finally");
  }
}
/**
 * 处理提交的参数
 */

const handleData = (data) => {
  //类型 1一级标题 2二级标题 3图片 4文字 5富文本
  let blocks = JSON.parse(JSON.stringify(drawingList.value));
  let newBlockList = [];
  newBlockList.push({
    //item.articleId = item.label
    type: 5,
    text: item.typeId === typeIdEnum.picture ? item?.defaultValue[0]?.url : item.defaultValue,
    sort: index + 1,
  });
  return newBlockList;
};
/**
 * 编辑文章的值处理
 */
const defaltBaseFormData = ref({});
const blockId = ref(null);
const editDefaultData = () => {
  cmsArticle.id = props.defaultData.id;
  console.log(props.defaultData, "props.defaultData");
  // 处理baseform的数据
  defaltBaseFormData.value = {
    title: props.defaultData.title,
    sort: props.defaultData.sort,
    categoryId: props.defaultData.categoryId,
    image: props.defaultData.image,
    text: props.defaultData.blocks[0]?.text ?? "",
  };
  blockId.value = props.defaultData.blocks[0]?.id ?? null;
  // props.defaultData.blocks.forEach(item => {
  //   let defaultValue = item.text
  //   if (item.type == typeIdEnum.picture) {
  //     defaultValue = [{
  //       name: item.text,
  //       url: item.text
  //     }]
  //   }
  //   addComponent({
  //     ...articleConfigObjectComponents[item.type],
  //     defaultValue: defaultValue,
  //   })
  // })
};

onMounted(() => {
  if (props.defaultData) {
    editDefaultData();
    console.log(props.articleExtraJson);
  }
});
const dymaticRules = ref([]);
watchEffect(() => {
  dymaticRules.value = {};
  drawingList.value.forEach((item) => {
    dymaticRules.value[item.vModel] = {
      required: true,
      message: item.placeholder,
      trigger: "change",
    };
  });
});
</script>

<style lang="scss">
$lighterBlue: #409eff;

.container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #fff;
  //background-color: var(--el-bg-color-overlay);
  //height: calc(100vh - 50px - 40px);
  display: flex;

  .left-board {
    width: 300px;
    padding: 0 20px;

    .left-scrollbar {
      .el-scrollbar__wrap {
        box-sizing: border-box;
        overflow-x: hidden !important;
        margin-bottom: 0 !important;

        .components-list {
          padding: 8px;
          box-sizing: border-box;
          height: 100%;

          .components-title {
            font-size: 14px;
            // color: #222;
            margin: 6px 2px;

            .svg-icon {
              // color: #666;
              font-size: 18px;
              margin-right: 5px;
            }
          }

          .components-draggable {
            padding-bottom: 20px;

            .components-item {
              display: inline-block;
              text-align: center;
              width: 100%;
              margin: 1%;
              transition: transform 0ms !important;

              .components-body {
                padding: 8px 10px;
                background: var(--el-border-color-extra-light);
                font-size: 12px;
                cursor: move;
                border: 1px dashed var(--el-border-color-extra-light);
                border-radius: 3px;

                .svg-icon {
                  // color: #777;
                  font-size: 15px;
                  margin-right: 5px;
                }

                &:hover {
                  border: 1px dashed #787be8;
                  color: #787be8;

                  .svg-icon {
                    color: #787be8;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .center-board {
    position: relative;
    flex: 1;
    margin-left: 10px;
    box-sizing: border-box;
    background-color: #fff;
    padding: 10px 20px;
    .center-title {
      position: absolute;
      left: 20px;
    }
    .action-bar {
      position: relative;
      box-sizing: border-box;
      padding: 10px 0 15px 0;
      border-bottom: 1px solid var(--el-border-color-extra-light);
      display: flex;
      align-items: center;
      justify-content: flex-end;

      u .delete-btn {
        color: #f56c6c;
      }
    }

    .empty-info {
      text-align: center;
      font-size: 18px;
      color: #ccb1ea;
      letter-spacing: 4px;
    }

    .center-scrollbar {
      height: 40vh;
      border-left: 1px solid var(--el-border-color-extra-light);
      border-right: 1px solid var(--el-border-color-extra-light);
      box-sizing: border-box;

      .el-scrollbar__view {
        overflow-x: hidden;
      }

      .center-board-row {
        padding: 12px 12px 15px 12px;
        box-sizing: border-box;

        & > .el-form {
          // 69 = 12+15+42
          //height: calc(100vh - 50px - 40px - 69px);
          flex: 1;

          .drawing-board {
            height: 100%;
            position: relative;

            .components-body {
              padding: 0;
              margin: 0;
              font-size: 0;
            }

            .sortable-ghost {
              position: relative;
              display: block;
              overflow: hidden;

              &::before {
                content: " ";
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                height: 3px;
                background: rgb(89, 89, 223);
                z-index: 2;
              }
            }

            .components-item.sortable-ghost {
              width: 100%;
              height: 60px;
              background: var(--el-border-color-extra-light);
            }

            .active-from-item {
              & > .el-form-item {
                background: var(--el-border-color-extra-light);
                border-radius: 6px;
              }

              & > .drawing-item-copy,
              & > .drawing-item-delete {
                display: initial;
              }

              & > .component-name {
                color: $lighterBlue;
              }

              .el-input__wrapper {
                box-shadow: 0 0 0 1px var(--el-input-hover-border-color) inset;
              }
            }

            .el-form-item {
              margin-bottom: 15px;
            }
          }

          .drawing-item {
            position: relative;
            cursor: move;

            &.unfocus-bordered:not(.activeFromItem) > div:first-child {
              border: 1px dashed #ccc;
            }

            .el-form-item {
              padding: 12px 10px;
            }
          }

          .drawing-row-item {
            position: relative;
            cursor: move;
            box-sizing: border-box;
            border: 1px dashed #ccc;
            border-radius: 3px;
            padding: 0 2px;
            margin-bottom: 15px;

            .drawing-row-item {
              margin-bottom: 2px;
            }

            .el-col {
              margin-top: 22px;
            }

            .el-form-item {
              margin-bottom: 0;
            }

            .drag-wrapper {
              min-height: 80px;
              flex: 1;
              display: flex;
              flex-wrap: wrap;
            }

            &.active-from-item {
              border: 1px dashed $lighterBlue;
            }

            .component-name {
              position: absolute;
              top: 0;
              left: 0;
              font-size: 12px;
              color: #bbb;
              display: inline-block;
              padding: 0 6px;
            }
          }

          .drawing-item,
          .drawing-row-item {
            &:hover {
              & > .el-form-item {
                background: var(--el-border-color-extra-light);
                border-radius: 6px;
              }

              & > .drawing-item-copy,
              & > .drawing-item-delete {
                display: initial;
              }
            }

            & > .drawing-item-copy,
            & > .drawing-item-delete {
              display: none;
              position: absolute;
              top: -10px;
              width: 22px;
              height: 22px;
              line-height: 22px;
              text-align: center;
              border-radius: 50%;
              font-size: 12px;
              border: 1px solid;
              cursor: pointer;
              z-index: 1;
            }

            & > .drawing-item-copy {
              right: 56px;
              border-color: $lighterBlue;
              color: $lighterBlue;
              background: #fff;

              &:hover {
                background: $lighterBlue;
                color: #fff;
              }
            }

            & > .drawing-item-delete {
              right: 24px;
              border-color: #f56c6c;
              color: #f56c6c;
              background: #fff;

              &:hover {
                background: #f56c6c;
                color: #fff;
              }
            }
          }
        }
      }
    }
  }
}
</style>
